package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ReceiptAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.Query;
import com.isunland.managesystem.entity.RProInvoiceRecd;
import com.isunland.managesystem.entity.ReceiptListOriginal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 企业开票申请列表
 *
 * @author wangyanan
 */
public class ReceiptListFragmenet extends BaseListFragment {
  protected static final int ADD = 1;// 添加
  protected static final int EDIT = 2;// 修改
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核
  private static final int REQUEST_ADD = 0;
  private static final int REQUEST_QUERY = 1;
  private static final int REQUEST_DETAIL = 2;
  private ReceiptAdapter mAdapter;
  private int mPage = 1;// 请求第几页的数据.
  private Query mQuery = new Query("", "全部", "30", "近一个月", "", "");
  private ArrayList<RProInvoiceRecd> mList;
  // private boolean isQuery;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.receiptWrite);
  }

  @Override public void initData() {
    super.initData();
    mList = new ArrayList<>();
    mAdapter = new ReceiptAdapter(mActivity, mList);
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setListAdapter(mAdapter);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mPullRefreshListView.setMode(Mode.BOTH);
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();

    params.put("invoiceKind", "out");
    params.put("joNo", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("memCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("page", mPage + "");
    params.put("rows", "20");
    params.put("sort", "order_no");
    params.put("order", "desc");

    //		params.put("regDate", "desc");
    // 筛选.

    if (!TextUtils.isEmpty(mQuery.getDataStatusKey())) {

      params.put("dataStatus", mQuery.getDataStatusKey());
    }
    if (!TextUtils.isEmpty(mQuery.getRegisterTimeKey())) {

      params.put("timeRange", mQuery.getRegisterTimeKey());
    }
    if (!TextUtils.isEmpty(mQuery.getReceiptStartTime())) {

      params.put("beginoccurDate", mQuery.getReceiptStartTime());
    }
    if (!TextUtils.isEmpty(mQuery.getReceiptEndTime())) {

      // params.put("beginoccurDate", mQuery.getReceiptStartTime());
      params.put("endoccurDate", mQuery.getReceiptEndTime());
    }

    return params;
  }

  @Override public String getUrl() {
    return ApiConst.URL_RECEIPT_LIST;
  }

  @Override public void resolveResponse(String json) {

    ReceiptListOriginal original = new Gson().fromJson(json, ReceiptListOriginal.class);
    ArrayList<RProInvoiceRecd> rows = original.getRows();
    // List<RProInvoiceRecd> rows = testData(mPage);
    setAdapter(rows);
  }

  private List<RProInvoiceRecd> testData(int page) {
    List<RProInvoiceRecd> rows = new ArrayList<>();

    for (int i = 0; i < 20; i++) {
      int suffix = (page - 1) * 20 + i;
      RProInvoiceRecd item = new RProInvoiceRecd();
      item.setId(UUID.randomUUID().toString());
      item.setContractName("合同名" + suffix);
      item.setContent("事务内容" + suffix);
      item.setContractAmount((Math.random() * 10000));
      item.setDataStatus(getDataStatus());
      rows.add(item);
    }
    return rows;
  }

  private String getDataStatus() {
    int type = (int) (Math.random() * 4);
    switch (type) {
      case 0:
        return DataStatus.NEW;

      case 1:

        return DataStatus.CHECK_PASS;
      case 2:

        return DataStatus.WAIT_CHECK;
      case 3:

        return DataStatus.ABORT;
      default:
        break;
    }
    return null;
  }

  private void setAdapter(ArrayList<RProInvoiceRecd> detail) {
    if (detail == null) {
      detail = new ArrayList<>();
    }
    if (mPage == 1) {
      mList.clear();
    }
    mList.addAll(detail);
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_add_search, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_add:
        Intent i = new Intent(getActivity(), ReceiptInfoActivity.class);
        startActivityForResult(i, REQUEST_ADD);
        break;

      case R.id.menu_item_querys:
        intent = new Intent(getActivity(), ReceiptQueryActicity.class);
        intent.putExtra(ReceiptQueryFragment.EXTRA_QUERY, mQuery);
        startActivityForResult(intent, REQUEST_QUERY);

        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_ADD) {

      //			mPage = 1;
      //			volleyPost();

      mPullRefreshListView.setMode(Mode.PULL_FROM_START);
      mPage = 1;
      volleyPost();
      mPullRefreshListView.setMode(Mode.BOTH);
    }
    if (requestCode == REQUEST_DETAIL) {

      //			mPage = 1;
      //			volleyPost();

      mPullRefreshListView.setMode(Mode.PULL_FROM_START);
      mPage = 1;
      volleyPost();
      mPullRefreshListView.setMode(Mode.BOTH);
    }
    if (requestCode == REQUEST_QUERY) {
      //			mPage = 1;
      //			// isQuery = true;
      //			mQuery = (Query) data.getSerializableExtra(ReceiptQueryFragment.EXTRA_QUERY);
      //			volleyPost();

      mPullRefreshListView.setMode(Mode.PULL_FROM_START);
      mPage = 1;
      // isQuery = true;
      mQuery = (Query) data.getSerializableExtra(ReceiptQueryFragment.EXTRA_QUERY);
      volleyPost();
      mPullRefreshListView.setMode(Mode.BOTH);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    Intent i = new Intent(getActivity(), ReceiptInfoActivity.class);
    i.putExtra(ReceiptInfoFragment.EXTRA_RECEIPT, mAdapter.getItem(position - 1));
    startActivityForResult(i, REQUEST_DETAIL);
    super.onListItemClick(l, v, position, id);
  }
}
